package org.lqk.guice;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import org.lqk.guice.controller.UserController;
import org.lqk.guice.service.IUserService;
import org.lqk.guice.service.impl.UserService;

/**
 * Created by bert on 2017/5/4.
 */
public class InjectorUtils {
    private static Injector s_injector;
    private static Object lock = new Object();

    private static Injector getInjector() {
        if (s_injector == null) {
            synchronized (lock) {
                if (s_injector == null) {
                    try {
                        s_injector = Guice.createInjector(new AbstractModule() {
                            @Override
                            protected void configure() {
                                bind(IUserService.class).to(UserService.class).in(Singleton.class);
                                bind(UserController.class).in(Singleton.class);
                            }
                        });
                    } catch (Throwable ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }

        return s_injector;
    }

    public static <T> T getInstance(Class<T> clazz) {
        try {
            return getInjector().getInstance(clazz);
        } catch (Throwable ex) {
            throw new RuntimeException(ex);
        }
    }

}
